//
//  UITextView+Emoticon.swift
//  图文混排
//
//  Created by QinXin on 15/7/7.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit

extension UITextView {
    
    func insertEmoticon(emoticon: QXEmoticon) {
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji ?? "")
        }
        
        if emoticon.chs != nil {
            
            
            
//            let attachment = QXEmoticonAttachment()
//            attachment.chs = emoticon.chs
//            attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
//            attachment.bounds = CGRect(x: 0, y: -4, width: font!.lineHeight, height: font!.lineHeight)
//            let imageAttr = NSAttributedString(attachment: attachment)
            
            let imageAttr = QXEmoticonAttachment.emoticonString(emoticon, font: font!)
            
            let mattr = NSMutableAttributedString(attributedString: attributedText)
            mattr.replaceCharactersInRange(selectedRange, withAttributedString: imageAttr)
            
            // 记录光标位置
            let tmpRange = selectedRange
            
            
            // MARK : --
            // 设置表情图片的字体
            mattr.addAttributes([NSFontAttributeName: font!], range: NSMakeRange(tmpRange.location, 1))
            
            attributedText = mattr
            
            // 还原光标位置
            selectedRange = NSMakeRange(tmpRange.location + 1, 0)
        }
        
    }
    
    /// 返回 textView 完整字符串
    func emoticonText() -> String {
        var mStr = String()
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dic, range, _) -> Void in
            
            // 字典中包含 NSAttachment 为 表情
            // 否则是文字
            if let attachment = dic["NSAttachment"] as? QXEmoticonAttachment {
                mStr += attachment.chs ?? ""
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                mStr += str
            }
            
        }
        return mStr
    }

    
}
